package com.miao.im.server;

import com.lmax.disruptor.dsl.Disruptor;
import com.miao.im.common.Constant;
import com.miao.im.config.NettyProperties;
import com.miao.im.service.auth.IAuthManager;
import com.miao.im.support.delayqueue.DelayMessageManager;
import com.miao.im.support.disruptor.DisruptorEvent;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


/**
 * @Auther: miaoguoxin
 * @Date: 2021/2/24 14:43
 * @Description:
 */
@Slf4j
@Component
public class ServerStarter implements DisposableBean {
    @Autowired
    private NettyProperties nettyProperties;
    @Autowired
    private Disruptor<DisruptorEvent<?>> disruptor;
    @Autowired
    @Qualifier("socketAuthManager")
    private IAuthManager authManager;

    @PostConstruct
    public void start() {
        //防阻塞
        new Thread(this::startServer).start();
    }

    private void startServer() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workGroup)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_RCVBUF, 128 * 1024)
                .childOption(ChannelOption.SO_SNDBUF, 128 * 1024)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new HttpServerCodec());
                        pipeline.addLast(new ChunkedWriteHandler());
                        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                        //用于处理websocket
                        pipeline.addLast(new WebSocketServerProtocolHandler("/chat"));
                        //读空闲触发
                        pipeline.addLast(new IdleStateHandler(
                                nettyProperties.getReadBeatTime(),
                                nettyProperties.getWriteHeartBeatTime(),
                                nettyProperties.getHeartBeatTime(),
                                nettyProperties.getHeartBeatTimeUnit()));
                        //自定义的处理器
                        pipeline.addLast(new WebsocketAccessHandler());
                        pipeline.addLast(new ExceptionChannelHandler())
                        ;
                    }
                });
        try {
            bootstrap.bind(nettyProperties.getPort()).sync().addListener(future -> {
                        if (future.isSuccess()) {
                            Constant.SERVER_ACTIVE = true;
                            log.info("webSocket server listen on port : [{}]", nettyProperties.getPort());
                        } else {
                            log.error("webSocket server listen on port error : [{}]", nettyProperties.getPort());
                        }
                    }
            ).channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("netty启动异常", e);
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    @Override
    public void destroy() throws Exception {
        Constant.SERVER_ACTIVE = false;
        DelayMessageManager.getInstance().destroy();
        authManager.allOut();
        disruptor.shutdown();
        log.info("服务器已关闭");
    }
}
